package com.longway.app.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.longway.common.token.utils.TokenUtil;
import com.longway.core.toolbox.cache.ICache;
import com.longway.core.toolbox.dd.api.ApiConfigKit;

import java.util.Map;


public class DingSessionInterceptor implements Interceptor {

	@Override
    public void intercept(Invocation inv) {
		Controller c = inv.getController();
		String token = c.getRequest().getHeader("accessToken");
		//验证token是否有效
		try {
			Ret	ret = TokenUtil.parseData(token);
			if (ret.isOk()) {
				//先从缓存根据token获取小程序的用户信息
				ICache cache = ApiConfigKit.getCache();
				String apiResultStr = cache.get("ding:session:" + token);
				if(apiResultStr == null){
					inv.getController().renderJson(ret.set("code", "403"));
					return;
				}
				Map<String,String> dingUser = JsonKit.parse(apiResultStr, Map.class);
				c.setAttr("dingUser", dingUser);
			}else{
				inv.getController().renderJson(ret.set("code", "403"));
				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			inv.getController().renderJson(Ret.fail("msg", "token为空!").set("code", "403"));
			return;
		}
		inv.invoke();
	}
}



